import axios from 'axios'
import env from '@/assets/js/baseJS/env.js'
import signUtil  from '@/assets/js/util/sign.js'
import md5 from 'js-md5'
import { Dialog } from 'vant';
import router from '@/router/index.js'
axios.defaults.baseURL = env.ChatAPI.apiPath;
axios.defaults.headers['Accept'] = 'application/json';
axios.defaults.headers["Content-Type"] = "application/json";
axios.defaults.timeout = 30 * 1000;

// axios.defaults.headers["token"] = "application/json";


axios.interceptors.request.use(
  config => {
    if (localStorage.getItem('user')) { //判断token是否存在
      var user = JSON.parse(localStorage.getItem('user'));
      var token = user.token;
      var signKey = user.signKey;
      var data = JSON.parse(config.data)
      //排序后的 参数
      data.token=token;
      var params = signUtil.sortObjASCII(data);
      console.log("params:"+params);
      var sign = md5(params + 'signKey=' + signKey)
      config.headers.token = token;  //将token设置成请求头
      config.headers.sign = sign;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

// http response 拦截器
axios.interceptors.response.use(
  response => {
    if (response.data.code === 2) {
      console.log("token失效");
      Dialog.alert({
        message: '登录失效,请重新登录'
      }).then(() => {
        // on close
        router.replace("/login");
      });

    }
    return response;
  },
  error => {
    return Promise.reject(error);
  }
);


export default {
  get: url => axios.get(url),
  post: (url, params) => axios.post(url, JSON.stringify(params)),
  put: (url, params) => axios.put(url, JSON.stringify(params)),
  delete: url => axios.delete(url)
}
